<template>
  <div class="login">
    <van-nav-bar title="注册" left-text="返回" left-arrow @click-left="$router.go(-1)" />
    <h1 class="title">优点达注册</h1>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        left-icon="manager"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: tel, message: '手机号格式不正确' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        left-icon="lock"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { validator: pwd, message: '密码由大于等于6位的字母数字组成，字母开头' }
        ]"
      />
      <van-field
        v-model="repassword"
        type="password"
        left-icon="lock"
        label="确认密码"
        placeholder="确认密码"
        :rules="[
          { required: true, message: '请填写确认密码' },
          { validator: pwd, message: '密码由大于等于6位的字母数字组成，字母开头' },
          { validator: repwd, message: '两次密码不一致' }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>

    <router-link class="link" to="/login">有账号了，马上去登录</router-link>
  </div>
</template>

<script>
import { registerAPI } from '@/api/user'

export default {
  name: 'register-index',
  data () {
    return {
      username: '',
      password: '',
      repassword: '',
      tel: /^1\d{10}$/
      // pwd: /^[a-zA-Z]\w{5,}$/
    }
  },
  methods: {
    async onSubmit (values) {
      // console.log('submit', values)
      const data = await registerAPI(values)
      // console.log(data)
      this.$store.commit('updateToken', data.data.token)
      this.$toast.success(data.errmsg)
      if (data.errno === 0) {
        this.$router.push('/user')
      }
    },
    pwd (val) {
      return /^[a-zA-Z]\w{5,}$/.test(val)
    },
    repwd (val) {
      return val === this.password
    }
  }
}
</script>

<style scoped lang="less">
.login {
  .title {
    font-size: 60px;
    color: #1989fa;
    font-weight: 400;
    text-align: center;
  }
  .van-nav-bar {
    background-color: #1989fa;
    /deep/ .van-icon-arrow-left {
      color: white;
    }
    /deep/ .van-nav-bar__title {
      color: white;
    }
  }
  .link {
    float: right;
    margin-right: 35px;
    font-size: 13px;
  }
}
</style>
